# 
# configuration_helpers.rb
# 
# Created on 24/09/2007, 11:47:25
# 

module AutoRest
  module Configuration
    
    # With all options in place, i can use the data to provide helper methods.    
    class ARDataContainer

      # Based on the params of the request, find the parent model
      # (a same resource can have many parents).
      def parent_resource_model params
        return nil if !params || params.empty? || parent_resources.empty?
        
        candidates= {} # hash[Model]= id
        params.keys.each do |key|
          if foreing_models.has_key? key
            model= foreing_models[key]
            candidates[model]= params[key]
          end
        end
        
        return nil if candidates.empty?

        if candidates.size > 1
          choices= foreing_models.values.collect {|e|e.class_name}.join(',') 
          message= "AutoRest (#{__FILE__}): " \
            "Warning! more than one model could be choosed! Choosing first one of: #{choices}"
          logger.debug message
        end
        
        key= candidates.keys.first
        key.find_by_id(candidates[key])
      end
      
      # For building methods like zone_edit_customer_path / url, etc..
      def resource_method parent, action
        # Post rails 1.2.3 puts the action before the resource names
        "#{action}#{get_prefix(parent)}#{resource.singular}"
      end
      
      # For  building methods as zone_customers_path / url, etc...
      def resources_method parent, action
        # Post rails 1.2.3 puts the action before the resource names
        "#{action}#{get_prefix(parent)}#{resource.plural}"
      end
      
      # This determines if the column is for the id of the parent given as param.
      def is_column_for_current_parent column, parent_resource
        return false if parent_resources.empty?
        res= parent_resources.select{|resource| resource.model == parent_resource.class}
        return false if !res || res.empty?
        "#{res.first.singular}_id" == column.to_s
      end
      
    private
    
      # Choose a path prefix given a parent resource.
      def get_prefix parent
        par_res= parent ? parent_resources.select{ |r| r.model == parent.class }.first : nil
        
        par_res ? par_res.name_prefix : resource.name_prefix
      end

    end #class ARDataContainer  
  end #module Configuration
end #module AutoRest
    
    